import mediaLibrary from '@ohos.multimedia.mediaLibrary';
import Utils from './Utils';


export default class MyMedia {
    private utils = new Utils();
    private media = null;

    constructor(context) {
        //获取媒体库的实例，用于访问和修改用户等个人媒体数据信息（如音频、视频、图片、文档等）。
        this.media = mediaLibrary.getMediaLibrary(context);
    }

    /**
     * 获取图片资源
     */
    async getFileAssetsCb(): Promise<string> {
        let fileKeyObj = mediaLibrary.FileKey
        let imageType = mediaLibrary.MediaType.IMAGE
        let imagesfetchOp = {
            selections: fileKeyObj.MEDIA_TYPE + '= ?',
            selectionArgs: [imageType.toString()],
        };
        let uri = "";
        let myUtils = this.utils;
        try {
            //获取文件资源，使用callback方式返回异步结果。
            let fetchFileResult = await this.media.getFileAssets(imagesfetchOp);
            let fileAssetList = await fetchFileResult.getAllObject();
            fileAssetList.forEach(function (getAllObjectInfo) {
                myUtils.myLog("getAllObjectInfo.displayName : " + getAllObjectInfo.displayName);
                uri = getAllObjectInfo.uri;
                myUtils.myLog('getAllObjectInfo.uri :' + uri);
            });
        } catch (error) {
            myUtils.myErrLog('getFileAssetsCb: running failed,error = ' + error);
        }
        return uri;
    }

    /**
     * 获取文件资源
     */
    getTxtFileAssetsCb() {
        let fileKeyObj = mediaLibrary.FileKey
        let fileType = mediaLibrary.MediaType.FILE
        let filesfetchOp = {
            selections: fileKeyObj.MEDIA_TYPE + '= ?',
            selectionArgs: [fileType.toString()],
        };

        let myUtils = this.utils;
        //获取文件资源，使用callback方式返回异步结果。
        this.media.getFileAssets(filesfetchOp, (error, fetchFileResult) => {
            myUtils.myLog('mediaLibraryTest : ASSET_CALLBACK is running');
            if (fetchFileResult != undefined) {
                myUtils.myLog('mediaLibraryTest : ASSET_CALLBACK fetchFileResult success');
                fetchFileResult.getAllObject((err, fileAssetList) => {
                    if (fileAssetList != undefined) {
                        fileAssetList.forEach(function (getAllObjectInfo) {
                            myUtils.myLog("getAllObjectInfo.displayName : " + getAllObjectInfo.displayName);
                            let path = getAllObjectInfo.uri;
                            myUtils.myLog('getAllObjectInfo.uri :' + path);
                        });
                    }
                });
            }
        });
    }

    /**
     * 获取文件资源
     */
    getFileAssetsPromise() {
        let fileKeyObj = mediaLibrary.FileKey
        let imageType = mediaLibrary.MediaType.IMAGE
        let imagesfetchOp = {
            selections: fileKeyObj.MEDIA_TYPE + '= ?',
            selectionArgs: [imageType.toString()],
        };
        let myUtils = this.utils;
        //获取文件资源，使用Promise方式返回结果。
        this.media.getFileAssets(imagesfetchOp).then(function (fetchFileResult) {
            if (fetchFileResult != undefined) {
                myUtils.myLog("getFileAssets successfully: image number is " + fetchFileResult.getCount());
                myUtils.myLog('mediaLibraryTest : ASSET_CALLBACK fetchFileResult success');
                fetchFileResult.getAllObject((err, fileAssetList) => {
                    if (fileAssetList != undefined) {
                        fileAssetList.forEach(function (getAllObjectInfo) {
                            myUtils.myLog('getAllObjectInfo.displayName :' + getAllObjectInfo.displayName);
                            myUtils.myLog('getAllObjectInfo.uri :' + getAllObjectInfo.uri);
                        });
                    }
                });
            } else {
                myUtils.myLog("getFileAssets successfully: fetchFileResult is undefined");
            }
        }).catch(function (err) {
            myUtils.myLog("getFileAssets failed with error:" + err);
        });
    }

    /**
     * 创建媒体资源，使用callback方式返回结果。
     * 代码风格：await
     */
    async createAssetCallbackAwait() {
        // 使用Callback方式创建Image类型文件
        let mediaType = mediaLibrary.MediaType.IMAGE;
        let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
        const path = await this.media.getPublicDirectory(DIR_IMAGE);
        this.utils.myLog('createAsset running,path: ' + path);
        this.media.createAsset(mediaType, 'imageCallBack1.jpg', path + 'myPicture/', (err, fileAsset) => {
            if (fileAsset != undefined) {
                this.utils.myLog('createAsset successfully,relativePath: ' + fileAsset.relativePath);
            } else {
                this.utils.myErrLog('createAsset failed, message = ' + err);
            }
        });
    }

    /**
     * 创建媒体资源，使用callback方式返回结果。
     *
     * 代码风格：then
     */
    createAssetCallbackThen() {
        // 使用Callback方式创建Image类型文件
        let mediaType = mediaLibrary.MediaType.IMAGE;
        let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
        this.media.getPublicDirectory(DIR_IMAGE).then((path) => {
            this.utils.myLog('createAsset running,path: ' + path);
            this.media.createAsset(mediaType, 'imageCallBack2.jpg', path + 'myPicture/', (err, fileAsset) => {
                if (fileAsset != undefined) {
                    this.utils.myLog('createAsset successfully,relativePath: ' + fileAsset.relativePath);
                } else {
                    this.utils.myErrLog('createAsset failed, message = ' + err);
                }
            });
        });
    }

    /**
     * 创建文件资源，使用callback方式返回结果。
     *
     * 代码风格：then
     */
    createAssetCallbackThenTxt() {
        // 使用Callback方式创建Image类型文件
        let mediaType = mediaLibrary.FileKey;
        let fileType = mediaLibrary.MediaType.FILE;
        this.media.getPublicDirectory(fileType).then((path) => {
            this.utils.myLog('createAsset running,path: ' + path);
            this.media.createAsset(mediaType, 'test.txt', path + 'myDoc/', (err, fileAsset) => {
                if (fileAsset != undefined) {
                    this.utils.myLog('createAsset successfully,relativePath: ' + fileAsset.relativePath);
                } else {
                    this.utils.myErrLog('createAsset failed, message = ' + err);
                }
            });
        });
    }

    /**
     *  创建媒体资源，使用Promise方式返回结果。
     *  代码风格：then
     */
    createAssetPromiseThen() {
        let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA;
        let myUtils = this.utils;
        this.media.getPublicDirectory(DIR_CAMERA).then(function (dicResult) {
            myUtils.myLog("getPublicDirectory successfully:" + JSON.stringify(dicResult));
        }).catch(function (err) {
            myUtils.myErrLog("getPublicDirectory failed with error:" + err);
        });
    }

    /**
     *  创建媒体资源，使用Promise方式返回结果。
     *  代码风格：await
     */
    async createAssetPromiseAwait() {
        let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA;
        const dicResult = await this.media.getPublicDirectory(DIR_CAMERA).catch((err) => {
            this.utils.myErrLog("getPublicDirectory failed with error:" + err);
        });
        this.utils.myLog("getPublicDirectory successfully:" + JSON.stringify(dicResult));
    }
}